<template>
  <div style="background-color: #f6f6f6">
    <el-row>
      <el-col :offset="2" :span="20">
        <div class="dw-table-form" style="padding-left: 20px;">
          <el-form :inline="true" :model="group" class="dw-form-inline" size="medium">
            <el-form-item label="搜索">
              <el-input v-model="formInline.groupName" clearable="clearable"
                        placeholder="请输入要查询的群组"></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;">
              <el-button type="primary" @click="queryList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="dw-table">
          <div class="dw-table-title">
            <el-row :span="24" align="middle" justify="space-between" type="flex">
              <el-col :span="4"><h3>群组管理</h3></el-col>
              <el-col :span="20" style="text-align: right;">
                <el-button size="medium" type="primary" @click="openCreateGroup()">新建群组</el-button>
              </el-col>
            </el-row>
          </div>

          <el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" border="border" stripe
                    style="width: 100%">
            <el-table-column min-width="10%" type="index"></el-table-column>
            <el-table-column label="群组名称" min-width="20%" prop="groupname"></el-table-column>
            <el-table-column label="详细说明" min-width="40%" prop="introduction"></el-table-column>
            <el-table-column label="创建时间" min-width="15%" prop="createdDate" style="speak-time: initial">
              <template v-slot="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">{{
                    formatDate(scope.row.createdDate)
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="15%">
              <template slot-scope="scope">
                <el-tooltip content="编辑群组" effect="dark" placement="top">
                  <el-button circle content="编辑" icon="el-icon-edit" size="medium" type="primary"
                             @click="handleEdit(scope.row.id,scope.row.groupname,scope.row.introduction)"></el-button>
                </el-tooltip>
                <el-tooltip content="查看群组成员" effect="dark" placement="top">
                  <el-button circle content="编辑" icon="el-icon-user" size="medium" type="primary"
                             @click="openGroupUsers(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除群组" effect="dark" placement="top">
                  <el-button circle content="删除" icon="el-icon-delete" size="medium" type="danger"
                             @click="handleDelete(scope.row.id,scope.row.number)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="dw-pagination">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[5,10,20,50]"
              :total="total"
              background
              layout="sizes,prev, pager, next"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" append-to-body width="40%">
        <el-form ref="userForm" :model="groupForm" :rules="groupFormRules" label-position="top" status-icon>
          <el-form-item :label-width="formLabelWidth" label="设置群组名称" prop="groupName" style="margin-top: 0px;">
            <el-input v-model="groupForm.groupName" autocomplete="off" placeholder="请输入群组名称"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" class="dialog-form-item" label="群组详情"
                        prop="groupDescription">
            <el-input v-model="groupForm.groupDescription" autocomplete="off"
                      placeholder="请输入群组详情说明信息。"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveGroup()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-drawer :visible.sync="drawer" append-to-body title="群组成员情况">
        <template>
          <el-table :data="drawerGroup.answerers" border="border">
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="电话号码" prop="telnumber"></el-table-column>
            <el-table-column align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-tooltip content="移出群组" effect="dark" placement="top">
                  <el-button content="移出群组" icon="el-icon-remove-outline" type="danger"
                             @click="handleRemoveAnswerer(scope.row.id)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<script>

import {
  createGroup,
  deleteGroup,
  modifyGroup,
  queryAnswerers,
  queryGroupsByKeyword,
  removeAnswerer
} from "../../api/user/user-group";
import {DateFormat} from "../../utils/common";

export default {
  name: "userGroup",
  data() {
    return {
      timer: null,
      count: 0,
      currentUserId: '',
      currentUserName: 'devUser',
      drawerGroup: {
        id: null,
        name: '',
        introduction: '',
        number: 3,
        answerers: [
          // {id: '001', name: '测试答者1'},
          // {id: '002', name: '测试答者2'},
          // {id: '003', name: '测试答者3'},
        ],
      },
      drawer: false,
      group: {
        groupName: '',
        groupDescription: '',
        id: null,
      },
      tableData: [
        // {id: '10001', name: '群组1', introduction: '说明1', number: 0, createdDate: "2022-11-01"},
        // {id: '10002', name: '群组2', introduction: '说明1', number: 0, createdDate: "2022-11-01"},
        // {id: '10003', name: '群组3', introduction: '说明1', number: 0, createdDate: "2022-11-01"},
        // {id: '10004', name: '群组4', introduction: '说明1', number: 0, createdDate: "2022-11-01"},
        // {id: '10005', name: '群组5', introduction: '说明1', number: 1, createdDate: "2022-11-01"},

      ],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      formInline: {
        groupName: ''
      },
      dialogTitle: '创建群组',
      dialogFormVisible: false,
      groupForm: {
        id: null,
        groupName: '',
        groupDescription: '',
      },
      groupFormRules: {
        groupName: [
          {required: true, message: '请输入群组名称', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 18 个字符', trigger: 'blur'},
          {type: 'string', message: '请输入正确的群组名称', trigger: ['blur', 'change']}
        ],
        groupDescription: [
          {required: true, message: '请输入群组详细信息', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ]
      },
      formLabelWidth: '120px'
    }
  },
  created() {
    this.queryList()
  },
  methods: {
    formatDate(date) {
      return DateFormat(date)
    },
    handleRemoveAnswerer(answererId) {
      let groupId = this.drawerGroup.id
      console.log(groupId + ",," + answererId)
      removeAnswerer(groupId, answererId).then((res) => {
        this.$message(res.data.message)

        clearTimeout(this.timer); //清除延迟执行
        this.timer = setTimeout(() => {  //设置延迟执行
          queryAnswerers(groupId).then((res) => {
            this.drawerGroup.answerers = res.data.data
          })
        }, 1000)
      })
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
    },
    queryList() {
      const groupName = this.formInline.groupName
      console.log("groupName->>>>" + groupName);
      queryGroupsByKeyword(groupName).then((res) => {
        console.log("res----->")
        console.log(res);
        this.tableData = res.data.data
        this.total = this.tableData.length
        for (let i = 0; i < this.tableData.length; i++) {
          this.tableData[i].createdDate = DateFormat(this.tableData[i].createdDate)
        }
        console.log(this.total);
      })
    },
    openCreateGroup() {
      //初始化群组编辑对话框
      this.dialogTitle = '创建群组'
      this.groupForm.id = null
      this.groupForm.groupName = ''
      this.groupForm.groupDescription = ''
      //显示对话框
      this.dialogFormVisible = true
    },
    handleSaveGroup() {
      //不规范数据无效
      console.log(this.groupForm);
      console.log(this.groupForm.groupName.length);
      console.log(this.groupForm.groupDescription.length);
      if (this.groupForm.groupName.length < 1 || this.groupForm.groupName.length > 18) {
        this.$message("请输入合法信息")
        return
      } else if (this.groupForm.groupDescription.length < 1 || this.groupForm.groupDescription.length > 50) {
        this.$message("请输入合法信息")
        return
      }
      console.log("save")
      console.log(this.groupForm.id)
      if (this.groupForm.id == null) {
        console.log("create")
        createGroup(this.currentUserId, this.groupForm.groupName, this.groupForm.groupDescription).then((res) => {
          console.log(res.data.message);
          this.$message(res.data.message)
        })
      } else {
        modifyGroup(this.groupForm.id, this.groupForm.groupName, this.groupForm.groupDescription).then((res) => {
          this.$message(res.data.message)
        })
      }
      this.dialogFormVisible = false;

      this.delayFlush()
    },
    openGroupUsers(group) {
      console.log(group);
      this.drawerGroup.id = group.id
      this.drawerGroup.number = group.number
      //调用接口获取该群组下的所有答者
      queryAnswerers(group.id).then((res) => {
        this.drawerGroup.answerers = res.data.data
      })
      this.drawer = true;
    },
    handleEdit(id, groupName, groupDescription) {
      //初始化群组编辑对话框
      this.dialogTitle = '创建群组'
      this.groupForm.id = id
      this.groupForm.groupName = groupName
      this.groupForm.groupDescription = groupDescription
      //显示对话框
      this.dialogFormVisible = true
    },
    handleDelete(id, number) {
      if (number > 0) {
        this.$message("该群组存在用户，无法删除");
        return
      }
      this.$msgbox.confirm('确认删除此群组吗？', '删除警告', {
        type: 'warning',
        confirmButtonText: '确认删除'
      }).then(() => {
        deleteGroup(id).then((res) => {
          this.$message(res.data.message)
          this.delayFlush()
        })
      }).catch(() => {
      })
    },
    delayFlush() {
      clearTimeout(this.timer); //清除延迟执行
      this.timer = setTimeout(() => {  //设置延迟执行
        this.queryList(this.formInline.groupName)
      }, 1000)
    }
  }
}
</script>

<style scoped>
.dw-table-form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.dw-table {
  background: white;
  padding: 20px;
}

.dw-table .dw-table-title {
  padding-bottom: 20px;
  border-bottom: 1px solid #f3f3f3;
}

.dw-table .dw-table-title h3 {
  padding: 0px;
  margin: 0px;
}

.el-form-item {
  margin-bottom: 0px;
}

.dialog-form-item {
  margin-top: 20px;
}

.dw-pagination {
  padding-top: 20px;
  text-align: right;
}
</style>
